<?php
namespace app\api\controller\user;

// 底层控制器
use think\Controller;

class Auth extends Controller {
    // 构造函数

    public function __construct() {
        // 手动把父类的方法获取过来
        parent::__construct();

        $this->UserModel = model( 'User.User' );
        $this->ConfigModel = model( 'Config' );
        $this->RegionModel = model( 'Region' );
    }

    // 登录授权

    public function login() {
        if ( $this->request->isPost() ) {
            // 获取code
            $code = $this->request->post( 'code', '' );

            if ( !$code ) {
                $this->error( '临时授权失败！' );
                exit;
            }

            //调用微信接口
            $result = $this->code2ession( $code );

            $openid = isset( $result[ 'openid' ] ) ? $result[ 'openid' ] : '';

            if ( empty( $openid ) ) {
                $this->error( '微信授权失败！' );
                exit;
            }

            //根据openid判断是否有绑定用户, 有绑定用户就将用户信息返回, 没绑定就去绑定
            $User = $this->UserModel->where( [ 'openid' => $openid ] )->find();

            if ( $User ) {

                $data = [
                    'id'=>$User[ 'id' ],
                    'openid'=>$User[ 'openid' ],
                    'email'=>$User[ 'email' ],
                    'nickname'=>$User[ 'nickname' ],
                    'avatar'=>$User[ 'avatar_cdn' ],
                    'sex'=>$User[ 'sex' ],
                    'sex_text'=>$User[ 'sex_text' ],
                    'province'=>$User[ 'province' ],
                    'city'=>$User[ 'city' ],
                    'district'=>$User[ 'district' ],
                    'createtime'=>$User[ 'createtime' ],
                    'content'=>$User[ 'content' ],
                    'point'=>$User[ 'point' ],
                    'vip'=>$User[ 'vip' ],
                    'auth'=>$User[ 'auth' ],
                    'cover'=>$User[ 'cover_cdn' ],
                    'region'=>explode( '-', $User[ 'region' ] ),
                    'region_text'=>$User[ 'region' ]
                ];

                $this->success( '登录成功', '', $data );
                exit;

            } else {
                $this->success( '请先关联账号', '/pages/user/bind', null );
                exit;
            }
        }
    }

    // 微信服务端发送GET请求

    public function code2ession( $js_code = null ) {
        if ( $js_code ) {

            $appid = 'wxed481f08ad68e62e';

            $appSecret = '709a0ebc0383deaed71e60b4b56f4b2e';

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appSecret&js_code=$js_code&grant_type=authorization_code";

            //发起get请求
            $result = $this->https_request( $url );

            //获取结果 将json转化为数组
            $resultArr = json_decode( $result, true );

            return $resultArr;

        } else {

            return false;
        }
    }

    //http请求 利用php curl扩展去发送get 或者 post请求 服务器上面一定要开启 php curl扩展
    // https://www.php.net/manual/zh/book.curl.php
    protected function https_request( $url, $data = null ) {
        if ( function_exists( 'curl_init' ) ) {
            $curl = curl_init();
            curl_setopt( $curl, CURLOPT_URL, $url );
            curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
            curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
            curl_setopt( $curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1 );
            if ( !empty( $data ) ) {
                curl_setopt( $curl, CURLOPT_POST, 1 );
                curl_setopt( $curl, CURLOPT_POSTFIELDS, $data );
            }
            curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
            // 发送会话，返回结果
            $output = curl_exec( $curl );
            curl_close( $curl );
            return $output;
        } else {
            return false;
        }
    }

    // 登录授权appid

    public function bind() {
        if ( $this->request->isPost() ) {
            // 获取code
            $code = $this->request->post( 'code', '' );
            $email = $this->request->post( 'email', '' );
            $password = $this->request->post( 'password', '' );

            if ( !$code ) {
                $this->error( '临时授权失败！' );
                exit;
            }

            //调用微信接口
            $result = $this->code2ession( $code );

            $openid = isset( $result[ 'openid' ] ) ? $result[ 'openid' ] : '';

            if ( empty( $openid ) ) {
                $this->error( '微信授权失败！' );
                exit;
            }

            // 根据openid判断是否有绑定用户，有绑定用户就将用户信息返回，没有绑定就去绑定
            $Useropenid = $this->UserModel->where( [ 'openid' => $openid ] )->find();

            if ( $Useropenid ) {
                $data = [
                    'id'=>$Useropenid[ 'id' ],
                    'openid'=>$Useropenid[ 'openid' ],
                    'email'=>$Useropenid[ 'email' ],
                    'nickname'=>$Useropenid[ 'nickname' ],
                    'avatar'=>$Useropenid[ 'avatar_cdn' ],
                    'sex'=>$Useropenid[ 'sex' ],
                    'sex_text'=>$Useropenid[ 'sex_text' ],
                    'province'=>$Useropenid[ 'province' ],
                    'city'=>$Useropenid[ 'city' ],
                    'district'=>$Useropenid[ 'district' ],
                    'createtime'=>$Useropenid[ 'createtime' ],
                    'content'=>$Useropenid[ 'content' ],
                    'point'=>$Useropenid[ 'point' ],
                    'vip'=>$Useropenid[ 'vip' ],
                    'auth'=>$Useropenid[ 'auth' ],
                    'cover'=>$Useropenid[ 'cover_cdn' ],
                    'region'=>explode( '-', $Useropenid[ 'region' ] ),
                    'region_text'=>$Useropenid[ 'region' ]
                ];

                $this->success( '您已经绑定过，无须重复绑定', null, $data );
                exit;
            }

            // 查询数据库是否有该用户
            $User = $this->UserModel->where( [ 'email' => $email ] )->find();

            // 数据库没有该用户，就注册用户
            if ( !$User ) {
                // 生成密码盐
                $salt = randstr( 10 );

                // 密码加密
                $password = md5( $password.$salt );

                // 获取系统配置表里面的赠送积分 value 查询某个字段的值
                $RegisterPoint = $this->ConfigModel->where( [ 'key' => 'RegisterPoint' ] )->value( 'value' );

                // 判断注册积分 是不是一个整数 is_numeric() 函数用于检测变量是否为数字或数字字符。
                $RegisterPoint = is_numeric( $RegisterPoint ) ? abs( $RegisterPoint ) : 0;

                // 组装数据
                $data = [
                    'email' => $email,
                    'nickname' => $email,
                    'password' => $password,
                    'salt' => $salt,
                    'point' => $RegisterPoint,
                    'vip' => 0,
                    'auth' => 0,
                    'openid' => $openid,
                ];

                // 开始插入数据库 validate
                $res = $this->UserModel->validate( 'common/User/User' )->save( $data );

                if ( $res === FALSE ) {
                    // 注册失败
                    // getError 返回操作的结果
                    $this->error( $this->UserModel->getError() );
                    exit;
                } else {
                    // 注册成功
                    $User = $this->UserModel->where( [ 'openid' => $openid ] )->find();

                    $data = [
                        'id'=>$User[ 'id' ],
                        'openid'=>$User[ 'openid' ],
                        'email'=>$User[ 'email' ],
                        'nickname'=>$User[ 'nickname' ],
                        'avatar'=>$User[ 'avatar_cdn' ],
                        'sex'=>$User[ 'sex' ],
                        'sex_text'=>$User[ 'sex_text' ],
                        'province'=>$User[ 'province' ],
                        'city'=>$User[ 'city' ],
                        'district'=>$User[ 'district' ],
                        'createtime'=>$User[ 'createtime' ],
                        'content'=>$User[ 'content' ],
                        'point'=>$User[ 'point' ],
                        'vip'=>$User[ 'vip' ],
                        'auth'=>$User[ 'auth' ],
                        'cover'=>$User[ 'cover_cdn' ],
                        'region'=>explode( '-', $User[ 'region' ] ),
                        'region_text'=>$User[ 'region' ]
                    ];

                    //注册成功，跳转到登录界面
                    $this->success( '注册并绑定成功', null, $data );
                    exit;
                }
            }

            // 数据库有该用户，就给该用户添加appid
            else {
                // 判断openid是否为空
                if ( !empty( $User[ 'openid' ] ) ) {
                    $this->error( '您输入的邮箱已被绑定，无法再次绑定' );
                    exit;
                }

                // 密码加密
                $password = md5( $password.$User[ 'salt' ] );

                // 判断密码是否正确
                if ( $password != $User[ 'password' ] ) {
                    $this->error( '您绑定的账号密码输入错误！' );
                    exit;
                }

                // 组装数据
                $data = [
                    'id' => $User[ 'id' ],
                    'openid' => $openid,
                ];

                // 更新数据库
                $result = $this->UserModel->isUpdate()->save( $data );

                if ( $result === false ) {
                    $this->error( $this->UserModel->getError() );
                    exit;
                } else {
                    //重新查询最新的数据返回
                    $check = $this->UserModel->where( [ 'email' => $email ] )->find();

                    $data = [
                        'id'=>$check[ 'id' ],
                        'openid'=>$check[ 'openid' ],
                        'email'=>$check[ 'email' ],
                        'nickname'=>$check[ 'nickname' ],
                        'avatar'=>$check[ 'avatar_cdn' ],
                        'sex'=>$check[ 'sex' ],
                        'sex_text'=>$check[ 'sex_text' ],
                        'province'=>$check[ 'province' ],
                        'city'=>$check[ 'city' ],
                        'district'=>$check[ 'district' ],
                        'createtime'=>$check[ 'createtime' ],
                        'content'=>$check[ 'content' ],
                        'point'=>$check[ 'point' ],
                        'vip'=>$check[ 'vip' ],
                        'auth'=>$check[ 'auth' ],
                        'cover'=>$check[ 'cover_cdn' ],
                        'region'=>explode( '-', $check[ 'region' ] ),
                        'region_text'=>$check[ 'region' ],
                    ];

                    $this->success( '绑定成功', null, $data );
                    exit;
                }
            }

        }
    }

    // 修改资料

    public function profile() {
        if ( $this->request->isPost() ) {
            $param = $this->request->param();

            //获取用户id
            $userid = $this->request->param( 'id', 0 );

            $User = $this->UserModel->find( $userid );

            if ( !$User ) {
                $this->error( '用户不存在' );
                exit;
            }

            // 组装数据
            $data = [
                'id' => $userid,
                'nickname' => $param[ 'nickname' ],
                'sex' => $param[ 'sex' ],
                'content' => $param[ 'content' ]
            ];

            // 获取城市信息
            $region = $this->request->param( 'region', 0 );

            // 判断城市信息是否存在
            if ( !empty( $region ) ) {
                // 查询地区数据
                $parentpath = $this->RegionModel->where( [ 'code' => $region ] )->value( 'parentpath' );

                if ( empty( $parentpath ) ) {
                    $this->error( '您所选择的地区不存在，请重新选择' );
                    exit;
                }

                // 将字符串转换为数组
                $path = explode( ',', $parentpath );

                if ( count( $path ) <= 0 ) {
                    $this->error( '您所选择的地区不存在，请重新选择' );
                    exit;
                }

                // 组装地区信息
                if ( isset( $path[ 0 ] ) ) {
                    $data[ 'province' ] = $path[ 0 ];
                }

                if ( isset( $path[ 1 ] ) ) {
                    $data[ 'city' ] = $path[ 1 ];
                }

                if ( isset( $path[ 2 ] ) ) {
                    $data[ 'district' ] = $path[ 2 ];
                }
            }

            // 封面上传
            if ( isset( $_FILES[ 'cover' ] ) && $_FILES[ 'cover' ][ 'size' ] > 0 ) {

                $coverUrl = upload( 'cover' );
                if ( $coverUrl == false ) {
                    $this->error( '上传封面图片失败' );
                    exit;
                }

                // 组装封面信息
                $data[ 'cover' ] = 'uploads/'.$coverUrl;
            }

            // 更新数据
            $result = $this->UserModel->isUpdate()->save( $data );

            // 判断数据是否更新
            if ( $result === false ) {
                // 更新失败
                // 删除上传上来的图片
                @is_file( $data[ 'cover' ] ) && @unlink( $data[ 'cover' ] );

                $this->error( '修改个人资料失败！' );
                exit;
            } else {
                // 更新成功
                // 删除旧的图片

                if ( @is_file( $data[ 'cover' ] ) ) {
                    $cover = ltrim( $User[ 'cover' ]. '/' );
                    @is_file( $cover ) && @unlink( $cover );
                }

                // 查询是否修改成功，并回显
                $UserData = $this->UserModel->find( $userid );

                $data = [
                    'id'=>$UserData[ 'id' ],
                    'openid'=>$UserData[ 'openid' ],
                    'email'=>$UserData[ 'email' ],
                    'nickname'=>$UserData[ 'nickname' ],
                    'avatar'=>$UserData[ 'avatar_cdn' ],
                    'sex'=>$UserData[ 'sex' ],
                    'sex_text'=>$UserData[ 'sex_text' ],
                    'province'=>$UserData[ 'province' ],
                    'city'=>$UserData[ 'city' ],
                    'district'=>$UserData[ 'district' ],
                    'createtime'=>$UserData[ 'createtime' ],
                    'content'=>$UserData[ 'content' ],
                    'point'=>$UserData[ 'point' ],
                    'vip'=>$UserData[ 'vip' ],
                    'auth'=>$UserData[ 'auth' ],
                    'cover'=>$UserData[ 'cover_cdn' ],
                    'region'=>explode( '-', $UserData[ 'region' ] ),
                    'region_text'=>$UserData[ 'region' ]
                ];

                $this->success( '修改个人资料成功！', null, $data );
                exit;
            }
        }
    }
}
?>